import 'dart:math';

import 'package:chat_app_project/screens/messages/components/emoji_pick.dart';
import 'package:chat_app_project/util/file_util.dart';
// import 'package:ffmpeg_kit_flutter/stream_information.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:getwidget/components/button/gf_button.dart';
import 'package:image_picker/image_picker.dart';
import 'package:video_thumbnail/video_thumbnail.dart';
import 'package:wukongimfluttersdk/entity/channel.dart';
import 'package:wukongimfluttersdk/model/wk_image_content.dart';
import 'package:wukongimfluttersdk/model/wk_text_content.dart';
import 'package:wukongimfluttersdk/model/wk_video_content.dart';
import 'package:wukongimfluttersdk/wkim.dart';

import '../../../constants.dart';
import '../../../util/permission_util.dart';
import '../../../util/toast_util.dart';
import 'voice_record.dart';

final GlobalKey<_ChatInputFieldState> chatInputFieldKey = GlobalKey();

class ChatInputField extends StatefulWidget {
  WKChannel currentChannel;

  Function scrollToBottom;

  ChatInputField(
      {super.key, required this.currentChannel, required this.scrollToBottom});

  @override
  State<ChatInputField> createState() => _ChatInputFieldState();
}

class _ChatInputFieldState extends State<ChatInputField> {
  final TextEditingController _textEditingController = TextEditingController();
  final FocusNode _focusNode = FocusNode();

  bool _showEmojiPicker = false;
  bool _showVoiceRecord = false;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Container(
          padding: const EdgeInsets.symmetric(
              horizontal: kDefaultPadding / 2, vertical: kDefaultPadding / 2),
          decoration: BoxDecoration(
              color: Theme.of(context).scaffoldBackgroundColor,
              boxShadow: [
                BoxShadow(
                    blurRadius: 32,
                    offset: const Offset(0, 3),
                    color: const Color(0xff087949).withOpacity(0.3))
              ]),
          child: SafeArea(
              child: Row(
            children: [
              GestureDetector(
                onTap: () {
                  debugPrint(
                      "showVoiceRecord ============================= ");
                  showVoiceRecord();
                },
                child: const Icon(Icons.mic, color: kPrimaryColor),
              ),
              const SizedBox(width: kDefaultPadding * 0.5),
              Expanded(
                child: Container(
                  padding: const EdgeInsets.symmetric(
                      horizontal: kDefaultPadding * 0.5),
                  decoration: BoxDecoration(
                    color: kPrimaryColor.withOpacity(0.07),
                    borderRadius: BorderRadius.circular(40),
                  ),
                  child: Row(
                    children: [
                      // Icon(
                      //   Icons.voice_chat,
                      //   color: Theme.of(context)
                      //       .textTheme
                      //       .bodyLarge
                      //       ?.color
                      //       ?.withOpacity(0.64),
                      // ),
                      const SizedBox(width: kDefaultPadding / 2),
                      Expanded(
                        child: TextField(
                          focusNode: _focusNode,
                          onChanged: (v) {
                            setState(() {});
                          },
                          onTap: () {
                            widget.scrollToBottom();
                            _showVoiceRecord = false;
                            _showEmojiPicker = false;
                            setState(() {});
                          },
                          //点击其他地方隐藏键盘
                          // onTapOutside: (p) {
                          //   print("${p.position}");
                          //   // if (_focusNode.hasFocus) {
                          //   //   _focusNode.unfocus();
                          //   // }
                          //   setState(() {});
                          // },
                          controller: _textEditingController,
                          // decoration: const InputDecoration(hintText: '请输入内容'),
                          autofocus: false,
                          decoration: const InputDecoration(
                              border: InputBorder.none, hintText: '请输入...'),
                        ),
                      ),
                      GestureDetector(
                        onTap: () {
                          showEmojiPicker();
                          setState(() {});
                          widget.scrollToBottom();
                        },
                        child: Icon(
                          Icons.sentiment_satisfied_alt_outlined,
                          color: Theme.of(context)
                              .textTheme
                              .bodyLarge
                              ?.color
                              ?.withOpacity(0.64),
                        ),
                      ),
                      const SizedBox(width: kDefaultPadding / 4),
                    ],
                  ),
                ),
              ),
              _textEditingController.text != ''
                  ? GFButton(
                      // horizontalPadding: 0,
                      text: '发送',
                      onPressed: () {
                        if (_textEditingController.text != '') {
                          WKTextContent text =
                              WKTextContent(_textEditingController.text);
                          WKIM.shared.messageManager.sendMessage(
                              text,
                              WKChannel(widget.currentChannel.channelID,
                                  widget.currentChannel.channelType));
                          // WKVoiceContent voiceContent = WKVoiceContent(10);
                          // voiceContent.localPath = 'videoContent';
                          // voiceContent.waveform = 'waveform';
                          // WKIM.shared.messageManager.sendMessage(
                          //     voiceContent, WKChannel(channelID, channelType));
                          _textEditingController.text = '';
                        }
                      },
                    )
                  : GestureDetector(
                      onTap: () {
                        debugPrint(
                            "add_circle_outline ============================= ");
                        //上传文件
                        _handleTapUpload();
                      },
                      child: Icon(
                        Icons.add_circle_outline,
                        color: Theme.of(context)
                            .textTheme
                            .bodyLarge
                            ?.color
                            ?.withOpacity(0.64),
                      )),
            ],
          )),
        ),
        const SizedBox(width: kDefaultPadding / 2),
        _showEmojiPicker
            ? SizedBox(
                height: 250,
                child: EmojiPick(
                    textEditingController: _textEditingController,
                    onEmojiSelected: (c, e) {
                      setState(() {});
                    },
                    onBackspacePressed: () {
                      setState(() {});
                    }),
              )
            : Container(),
         _showVoiceRecord
            ?  SizedBox(
                height: 250,
                child: VoiceRecord(currentChannel: widget.currentChannel,),
              )
            : Container(),
      ],
    );
  }
  // 文本框失去焦点
  void textUnfocus() {
    _focusNode.unfocus();
    _showVoiceRecord = false;
    _showEmojiPicker = false;
    setState(() {});
  }
  // 显示语音录制
  void showVoiceRecord(){
    _focusNode.unfocus();
    _showVoiceRecord = true;
    _showEmojiPicker = _showEmojiPicker? false: _showEmojiPicker;
    setState(() {});
  }
  // 显示表情选择
  void showEmojiPicker(){
    _focusNode.unfocus();
    _showEmojiPicker = true;
    _showVoiceRecord = _showVoiceRecord? false: _showVoiceRecord;
    setState(() {});
  }

  /// 上传图片或视频
  void _takeAndUpload(TakeType type) async {
    // 申请相机、存储等权限
    var isGrantedCamera = await PermissionUtil.requestCameraPermission();
    var isGrantedPhotos = await PermissionUtil.requestPhotosPermission();
    // var isGrantedVideos = await PermissionUtil.requestVideosPermission();
    var isGrantedStorage = await PermissionUtil.requestStoragePermission();

    if (!isGrantedCamera) {
      ToastUtil.toast("未允许相机权限");
      return;
    }
    if (!(isGrantedPhotos || isGrantedStorage)) {
      ToastUtil.toast("未允许存储权限");
    }

    // if (!isGrantedPhotos) {
    //   ToastUtil.toast("未允许照片权限");
    //   return;
    // }
    // if (!isGrantedVideos) {
    //   ToastUtil.toast("未允许视频权限");
    //   return;
    // }
    // if (!isGrantedStorage) {
    //   ToastUtil.toast("未允许存储权限");
    //   return;
    // }

    XFile? pickedFile;
    // 打开相机
    if (type == TakeType.camera) {
      pickedFile = await ImagePicker().pickImage(source: ImageSource.camera);
    } else if (type == TakeType.gallery) {
      // 打开图库
      pickedFile = await ImagePicker().pickImage(source: ImageSource.gallery);
    } else if (type == TakeType.video) {
      // 打开图库
      pickedFile = await ImagePicker().pickVideo(source: ImageSource.gallery);
    } else {
      ToastUtil.toast("不支持上传该类型的文件");
      return;
    }
    // if (uploadType == UploadType.image) {
    //   pickedFile = await ImagePicker().pickImage(source: imageSource);
    // } else if (uploadType == UploadType.video) {
    //   pickedFile = await ImagePicker().pickVideo(source: imageSource);
    // } else {
    //   ToastUtil.toast("不支持上传该类型的文件");
    //   return;
    // }
    if (pickedFile != null) {
      if (type == TakeType.camera || type == TakeType.gallery) {
        // 选择的文件
        final imgBytes = await pickedFile.readAsBytes();
        var coverPath = "/${Random.secure().nextInt(1000000)}.jpg";
        var coverFile = await FileUtil.createTmpFile(coverPath, imgBytes);
        WKImageContent imageContent = WKImageContent(100, 200);
        imageContent.localPath = coverFile.path;
        WKIM.shared.messageManager
            .sendMessage(imageContent, widget.currentChannel);
      } else if (type == TakeType.video) {
        // 选择的文件
        String path = pickedFile.path;
        final imgBytes = await VideoThumbnail.thumbnailData(
          video: path,
          imageFormat: ImageFormat.JPEG,
          // maxWidth: 128, // specify the width of the thumbnail, let the height auto-scaled to keep the source aspect ratio
          // quality: 25,
        );
        if (imgBytes == null) {
          ToastUtil.toast("格式不支持!");
          return;
        }
        var coverPath = "/${Random.secure().nextInt(1000000)}.jpg";
        var coverFile = await FileUtil.createTmpFile(coverPath, imgBytes);
        debugPrint(" 封面图 ================ ${coverFile.path}");
        // var info = await FileUtil.getVideoFileInfo(path);
        // if (info == null || info.getMediaInformation() == null) {
        //   ToastUtil.toast("格式不支持!");
        //   return;
        // }
        // if (info.getMediaInformation()!.getStreams().isEmpty) {
        //   ToastUtil.toast("格式不支持!");
        //   return;
        // }
        // List<StreamInformation>? streams =
        //     info.getMediaInformation()!.getStreams();
        // Map<dynamic, dynamic>? videoInfo;
        // if (streams[0].getAllProperties()?["codec_type"] == "video") {
        //   videoInfo = streams[0].getAllProperties();
        // } else if (streams[1].getAllProperties()?["codec_type"] == "audio") {
        //   videoInfo = streams[1].getAllProperties();
        // }
        // if (videoInfo == null) {
        //   ToastUtil.toast("格式错误!");
        //   return;
        // }
        //时长
        // var second = videoInfo["duration"];
        var second = 1;
        // 宽高
        // var width = videoInfo["width"];
        var width = 100;
        // var height = videoInfo["height"];
        var height = 200;
        //消息构建
        WKVideoContent videoContent = WKVideoContent();
        videoContent.coverLocalPath = coverFile.path;
        videoContent.localPath = path;
        videoContent.height = height;
        videoContent.width = width;
        // videoContent.size = int.parse(info.getMediaInformation()!.getSize()!);
        videoContent.size = await pickedFile.length();
        // videoContent.second = double.parse(second).ceil();
        videoContent.second = second;
        WKIM.shared.messageManager
            .sendMessage(videoContent, widget.currentChannel);
      }
    }
  }

  /// 从底部弹出CupertinoActionSheet
  void _handleTapUpload() {
    showCupertinoModalPopup(
      context: context,
      builder: (BuildContext context) => _buildActionSheet(context),
    ).then((value) {});
  }

  /// 构建底部弹出菜单actionSheet
  Widget _buildActionSheet(BuildContext context) {
    return CupertinoActionSheet(
      title: const Text(
        '请选择',
      ),
      actions: <Widget>[
        CupertinoActionSheetAction(
          child: const Text(
            '相机',
            style: TextStyle(
              fontSize: 14.0,
            ),
          ),
          onPressed: () {
            // 打开相机拍照
            _takeAndUpload(TakeType.camera);
            // 关闭菜单
            Navigator.of(context).pop();
          },
        ),
        CupertinoActionSheetAction(
          child: const Text(
            '相册',
            style: TextStyle(
              fontSize: 14.0,
            ),
          ),
          onPressed: () {
            // 打开相册，选取照片
            _takeAndUpload(TakeType.gallery);
            // 关闭菜单
            Navigator.of(context).pop();
          },
        ),
        CupertinoActionSheetAction(
          child: const Text(
            '视频',
            style: TextStyle(
              fontSize: 14.0,
            ),
          ),
          onPressed: () {
            // 打开相册，选取视频
            _takeAndUpload(TakeType.video);
            // 关闭菜单
            Navigator.of(context).pop();
          },
        )
      ],
      cancelButton: CupertinoActionSheetAction(
        child: const Text(
          '取消',
          style: TextStyle(
            fontSize: 13.0,
            color: Color(0xFF666666),
          ),
        ),
        onPressed: () {
          // 关闭菜单
          Navigator.of(context).pop();
        },
      ),
    );
  }
}

/// 选取类型
enum TakeType {
  // 从相机拍照后选择
  camera,
  // 从图库中选择 图片
  gallery,
  // 从图库中选择 视频
  video
}
